//
//  MultipleLayersNode.cpp
//  NMGame-mobile
//
//  Created by nieming on 2018/8/21.
//

#include "MultipleLayersNode.hpp"
USING_NS_CC;

MultipleLayersNode * MultipleLayersNode::create(){
    MultipleLayersNode * ret = new (std::nothrow) MultipleLayersNode();
    if (ret && ret->init())
    {
        ret->autorelease();
    }
    else
    {
        CC_SAFE_DELETE(ret);
    }
    return ret;
}

MultipleLayersNode::MultipleLayersNode(){
    _zOrderLessZeroIndex = 0;
    _curFlag = 0;
    _canVisit = false;
    
}

MultipleLayersNode::~MultipleLayersNode(){
    
}

void MultipleLayersNode::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags, short curLayerNum, bool isEnd)
{
    if (curLayerNum == 0){
        bool isVisibleByCamera = isVisitableByVisitingCamera();
        if(!_visible || !isVisibleByCamera){
            _canVisit = false;
            return;
        }
        _canVisit = true;
        
        adaptRenderers();
        doLayout();
        
        _curFlag = processParentFlags(parentTransform, parentFlags);
        _zOrderLessZeroIndex = 0;
        Director* director = Director::getInstance();
        director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
        director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
        
        int i = 0;      // used by _children
        sortAllChildren();
        for( ; i < _children.size(); i++ )
        {
            auto node = _children.at(i);
            
            if ( node && node->getLocalZOrder() < 0 )
                node->visit(renderer, _modelViewTransform, _curFlag);
            else
                break;
        }
        _zOrderLessZeroIndex = i;
        if(isVisibleByCamera){
            this->draw(renderer, _modelViewTransform, _curFlag);
        }
        director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    }else if(_canVisit){
        ssize_t size = _children.size();
        short curIndex = _zOrderLessZeroIndex + curLayerNum -1;
        if(curIndex < size){
            if(isEnd){
                for(auto it=_children.cbegin()+curIndex, itCend = _children.cend(); it != itCend; ++it)
                    (*it)->visit(renderer, _modelViewTransform, _curFlag);
            }else{
                auto it = _children.cbegin() + curIndex;
                (*it)->visit(renderer, _modelViewTransform, _curFlag);
            }
        }
    }
}

void MultipleLayersNode::copyProp(ui::Widget* model){
    copyProperties(model);
}

MultipleLayersNode * MultipleLayersNode::createCloneInstance(){
    return MultipleLayersNode::create();
}





